package cn.lxq.week01.assignment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HelloClassLoader extends ClassLoader{
	public static void main(String[]args) {
		try {
			Object obj= new HelloClassLoader().findClass("Hello").newInstance();
			Class<? extends Object> cls = obj.getClass();
			Method m = cls.getDeclaredMethod("hello");
			m.setAccessible(true);
			m.invoke(obj, null);
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
//		System.out.println(HelloClassLoader.class.getResource("Hello.xlass").getPath());
//		System.out.println(HelloClassLoader.class.getClassLoader().getResource("Hello.xlass").getPath());
//		System.out.println(HelloClassLoader.class.getResource("/Hello.xlass").getPath());
		File file = new File(HelloClassLoader.class.getResource("Hello.xlass").getFile());
		FileInputStream fis=null;
		byte[] buffer = new byte[1024];
		int length=-1;
		try {
			fis = new FileInputStream(file);
			length=fis.read(buffer);
			if(-1==length) {
				return null;
			}
			for(int i=0; i<length; i++) {
				buffer[i] = (byte) ~buffer[i];
			}
//			FileReader fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(null!=fis) {
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				fis=null;
			}
		}
		return defineClass(name,buffer, 0, length);
	}
}
